<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />





  <link rel="alternate" href="/atom.xml" title="结网之路" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本章主要讲了自定义 View 及其触摸事件的处理，有一定的难度
GitHub 地址：完成第29章，未完成挑战完成第29章挑战1-设备旋转完成第29章挑战2-双指旋转矩形

1. 自定义 View（定制视图）Android 自带众多优秀的标准视图与组件，但有时为追求独特的应用视觉效果，我们仍需创建定制视图。尽管定制视图种类繁多，但无外乎分为以下两大类别。

简单视图。简单视图内部也可以很复杂;之所">
<meta property="og:type" content="article">
<meta property="og:title" content="Android编程权威指南（第二版）学习笔记（二十九）—— 第29章 定制视图与触摸事件">
<meta property="og:url" content="https://kniost.github.io/2017-03-13-cj0ag5y78002bifs62vox4qyr/index.html">
<meta property="og:site_name" content="结网之路">
<meta property="og:description" content="本章主要讲了自定义 View 及其触摸事件的处理，有一定的难度
GitHub 地址：完成第29章，未完成挑战完成第29章挑战1-设备旋转完成第29章挑战2-双指旋转矩形

1. 自定义 View（定制视图）Android 自带众多优秀的标准视图与组件，但有时为追求独特的应用视觉效果，我们仍需创建定制视图。尽管定制视图种类繁多，但无外乎分为以下两大类别。

简单视图。简单视图内部也可以很复杂;之所">
<meta property="og:updated_time" content="2017-03-14T09:10:04.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android编程权威指南（第二版）学习笔记（二十九）—— 第29章 定制视图与触摸事件">
<meta name="twitter:description" content="本章主要讲了自定义 View 及其触摸事件的处理，有一定的难度
GitHub 地址：完成第29章，未完成挑战完成第29章挑战1-设备旋转完成第29章挑战2-双指旋转矩形

1. 自定义 View（定制视图）Android 自带众多优秀的标准视图与组件，但有时为追求独特的应用视觉效果，我们仍需创建定制视图。尽管定制视图种类繁多，但无外乎分为以下两大类别。

简单视图。简单视图内部也可以很复杂;之所">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://kniost.github.io/2017-03-13-cj0ag5y78002bifs62vox4qyr/"/>





  <title> Android编程权威指南（第二版）学习笔记（二十九）—— 第29章 定制视图与触摸事件 | 结网之路 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">结网之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">临渊羡鱼，不如退而结网</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://kniost.github.io/2017-03-13-cj0ag5y78002bifs62vox4qyr/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="kniost">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="结网之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android编程权威指南（第二版）学习笔记（二十九）—— 第29章 定制视图与触摸事件
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-13T11:07:10+08:00">
                2017-03-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android编程权威指南学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">Android编程权威指南学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017-03-13-cj0ag5y78002bifs62vox4qyr/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017-03-13-cj0ag5y78002bifs62vox4qyr/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本章主要讲了自定义 View 及其触摸事件的处理，有一定的难度</p>
<p>GitHub 地址：<br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/d56f3711ddf5c7be62e44199e365682bb6a121a4" target="_blank" rel="external">完成第29章，未完成挑战</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/e2dc19ea90c7ceddb52217283cb0111c98f5d22d" target="_blank" rel="external">完成第29章挑战1-设备旋转</a><br><a href="https://github.com/kniost/Android-Programming-Big-Nerd-Ranch-Guide-2nd/commit/5819fc03bde8009a8fd1683f29056f3ff8df4427" target="_blank" rel="external">完成第29章挑战2-双指旋转矩形</a></p>
</blockquote>
<h1 id="1-自定义-View（定制视图）"><a href="#1-自定义-View（定制视图）" class="headerlink" title="1. 自定义 View（定制视图）"></a>1. 自定义 View（定制视图）</h1><p>Android 自带众多优秀的标准视图与组件，但有时为追求独特的应用视觉效果，我们仍需创建定制视图。尽管定制视图种类繁多，但无外乎分为以下两大类别。</p>
<ul>
<li>简单视图。简单视图内部也可以很复杂;之所以归为简单类别，是因为简单视图不包括子视图。而且，简单视图几乎总是会执行定制绘制。</li>
<li>聚合视图。聚合视图由其他视图对象组成。聚合视图通常管理着子视图，但不负责执行定制绘制。图形绘制任务都委托给了各个子视图。<br><strong>创建定制视图所需的三大步骤：</strong></li>
</ul>
<ol>
<li>选择超类。对于简单定制视图而言，View 是个空白画布，因此它作为超类最常见。对于聚合定制视图，我们应选择合适的超类布局，比如 FrameLayout。</li>
<li>继承选定的超类，并至少覆盖一个超类构造方法。</li>
<li>覆盖其他关键方法，以定制视图行为。</li>
</ol>
<h2 id="1-1-创建一个基本的自定义-View"><a href="#1-1-创建一个基本的自定义-View" class="headerlink" title="1.1 创建一个基本的自定义 View"></a>1.1 创建一个基本的自定义 View</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BoxDrawingView</span> <span class="keyword">extends</span> <span class="title">View</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">// 从代码中创建的时候调用</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BoxDrawingView</span><span class="params">(Context context)</span> </span>&#123;</div><div class="line">        <span class="keyword">this</span>(context, <span class="keyword">null</span>);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">// 从 xml 文件中 inflate 的时候调用</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BoxDrawingView</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</div><div class="line">        <span class="keyword">super</span>(context, attrs);</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<blockquote>
<p><strong>注意在引用时我们必须使用自定义 View 的全路径类名，这样布局 inflater 才能够找到它。</strong>布局 inflater 解析布局 XML 文件，并按视图定义创建 View 实例。如果元素名不是全路径类名，布局 inflater 会转而在 android.view 和 android.widget 包中寻找目标。如果目标视图类放置在其他包中，布局 inflater 将无法找到目标并最终导致应用崩溃。</p>
</blockquote>
<h2 id="1-2-处理触摸事件"><a href="#1-2-处理触摸事件" class="headerlink" title="1.2 处理触摸事件"></a>1.2 处理触摸事件</h2><p>因为我们的自定义 View 是 View 的子类，可以直接覆盖以下 View 方法：</p>
<p><code>public boolean onTouchEvent(MotionEvent event)</code></p>
<p>该方法接收一个 MotionEvent 类实例，MotionEvent 类可用来描述包括位置和动作的触摸事件。动作用于描述事件所处的阶段。</p>
<table>
<thead>
<tr>
<th style="text-align:left">动作常量</th>
<th style="text-align:left">动作描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">ACTION_DOWN</td>
<td style="text-align:left">手指触摸到屏幕</td>
</tr>
<tr>
<td style="text-align:left">ACTION_MOVE</td>
<td style="text-align:left">手指在屏幕上移动</td>
</tr>
<tr>
<td style="text-align:left">ACTION_UP</td>
<td style="text-align:left">手指离开屏幕</td>
</tr>
<tr>
<td style="text-align:left">ACTION_CANCEL</td>
<td style="text-align:left">父视图拦截了触摸事件</td>
</tr>
</tbody>
</table>
<p>我们的目的就是在一根手指放下的时候记录下放下的位置，移动时随之变化，放开时固定该矩形框。并且之前画的矩形框数据需要记录下来。<br>所以建立一个实体类用于记录按下的点和放开的点：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Box</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> PointF mOrigin;</div><div class="line">    <span class="keyword">private</span> PointF mCurrent;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Box</span><span class="params">(PointF origin)</span> </span>&#123;</div><div class="line">        mOrigin = origin;</div><div class="line">        mCurrent = origin;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后重写 onTouchEvent 并进行相应操作：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">private</span> Box mCurrentBox;</div><div class="line"><span class="keyword">private</span> List&lt;Box&gt; mBoxen = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</div><div class="line">	<span class="comment">// 每次有触摸事件都记录下现在的坐标</span></div><div class="line">    PointF current = <span class="keyword">new</span> PointF(event.getX(), event.getY());</div><div class="line">    String action = <span class="string">""</span>;</div><div class="line"></div><div class="line">    <span class="keyword">switch</span> (event.getActionMasked()) &#123;</div><div class="line">        <span class="keyword">case</span> MotionEvent.ACTION_DOWN:</div><div class="line">            action = <span class="string">"ACTION_DOWN"</span>;</div><div class="line">            <span class="comment">// 每次按下的时候在列表中中新增一个 Box</span></div><div class="line">            mCurrentBox = <span class="keyword">new</span> Box(current);</div><div class="line">            mBoxen.add(mCurrentBox);</div><div class="line">            <span class="keyword">break</span>;</div><div class="line">        <span class="keyword">case</span> MotionEvent.ACTION_MOVE:</div><div class="line">            action = <span class="string">"ACTION_MOVE"</span>;</div><div class="line">            <span class="keyword">if</span> (mCurrentBox != <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="comment">// 移动的时候都要重绘</span></div><div class="line">                mCurrentBox.setCurrent(current);</div><div class="line">                invalidate();</div><div class="line">            &#125;</div><div class="line">            <span class="keyword">break</span>;</div><div class="line">        <span class="keyword">case</span> MotionEvent.ACTION_UP:</div><div class="line">        	<span class="comment">// 抬起的时候不再指向最新的 Box</span></div><div class="line">            action = <span class="string">"ACTION_UP"</span>;</div><div class="line">            mCurrentBox = <span class="keyword">null</span>;</div><div class="line">            <span class="keyword">break</span>;</div><div class="line">        <span class="keyword">case</span> MotionEvent.ACTION_CANCEL:</div><div class="line">            action = <span class="string">"ACTION_CANCEL"</span>;</div><div class="line">            mCurrentBox = <span class="keyword">null</span>;</div><div class="line">            <span class="keyword">break</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    Log.i(TAG, action + <span class="string">" at x="</span> + current.x +</div><div class="line">           <span class="string">", y="</span> + current.y);</div><div class="line"></div><div class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="2-onDraw-方法内的图形绘制"><a href="#2-onDraw-方法内的图形绘制" class="headerlink" title="2. onDraw() 方法内的图形绘制"></a>2. onDraw() 方法内的图形绘制</h1><p>应用启动时，所有视图都处于无效状态。也就是说，视图还没有绘制到屏幕上。为解决这个问题，Android 调用了顶级 View 视图的 draw()方法。这会引起自上而下的链式调用反应。首先，视图完成自我绘制，然后是子视图的自我绘制，再然后是子视图的子视图的自我绘制，如此调用下去直至继承结构的末端。当继承结构中的所有视图都完成自我绘制后，最顶级 View 视图也就生效了。<br>为加入这种绘制，可覆盖以下 View 方法: <code>protected void onDraw(Canvas canvas)</code><br>Canvas 和 Paint 是 Android 系统的两大绘制类。</p>
<ul>
<li>Canvas 类拥有我们需要的所有绘制操作。其方法可决定绘在哪里以及绘什么，比如线条、<br>圆形、字词、矩形等。</li>
<li>Paint 类决定如何绘制。其方法可指定绘制图形的特征，例如是否填充图形、使用什么字<br>体绘制、线条是什么颜色等。 </li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="title">BoxDrawingView</span><span class="params">(Context context, AttributeSet attrs)</span> </span>&#123;</div><div class="line">    <span class="keyword">super</span>(context, attrs);</div><div class="line"></div><div class="line">    <span class="comment">// 颜色为好看的半透明红色的矩形画笔</span></div><div class="line">    mBoxPaint = <span class="keyword">new</span> Paint();</div><div class="line">    mBoxPaint.setColor(<span class="number">0x22ff0000</span>);</div><div class="line"></div><div class="line">    <span class="comment">// 颜色为米白的背景画笔</span></div><div class="line">    mBackgroundPaint = <span class="keyword">new</span> Paint();</div><div class="line">    mBackgroundPaint.setColor(<span class="number">0xfff8efe0</span>);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onDraw</span><span class="params">(Canvas canvas)</span> </span>&#123;</div><div class="line">    <span class="comment">// 每次画的时候先画出背景</span></div><div class="line">    canvas.drawPaint(mBackgroundPaint);</div><div class="line"></div><div class="line">	<span class="comment">// 然后画出每个绘制过的矩形</span></div><div class="line">    <span class="keyword">for</span> (Box box : mBoxen) &#123;</div><div class="line">        <span class="keyword">float</span> left = Math.min(box.getOrigin().x, box.getCurrent().x);</div><div class="line">        <span class="keyword">float</span> right = Math.max(box.getOrigin().x, box.getCurrent().x);</div><div class="line">        <span class="keyword">float</span> top = Math.min(box.getOrigin().y, box.getCurrent().y);</div><div class="line">        <span class="keyword">float</span> bottom = Math.max(box.getOrigin().y, box.getCurrent().y);</div><div class="line"></div><div class="line">        canvas.drawRect(left, top, right, bottom, mBoxPaint);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="3-挑战练习"><a href="#3-挑战练习" class="headerlink" title="3. 挑战练习"></a>3. 挑战练习</h1><h2 id="3-1-设备旋转问题"><a href="#3-1-设备旋转问题" class="headerlink" title="3.1 设备旋转问题"></a>3.1 设备旋转问题</h2><ol>
<li>首先，要给整个视图加上 ID，<code>onSaveInstanceState()</code>以及<code>onRestoreInstanceState()</code>方法才会被调用</li>
<li>使用 Bundle 传递需要存储的参数</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">protected</span> Parcelable <span class="title">onSaveInstanceState</span><span class="params">()</span> </span>&#123;</div><div class="line">    Bundle bundle = <span class="keyword">new</span> Bundle();</div><div class="line">    <span class="comment">// 存储父类需要存储的内容</span></div><div class="line">    Parcelable superData = <span class="keyword">super</span>.onSaveInstanceState();</div><div class="line">    bundle.putParcelable(KEY_SUPER_DATA, superData);</div><div class="line">    <span class="comment">// 存储所有的矩形</span></div><div class="line">    bundle.putSerializable(KEY_BOXEN, (ArrayList) mBoxen);</div><div class="line">    <span class="keyword">return</span> bundle;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onRestoreInstanceState</span><span class="params">(Parcelable state)</span> </span>&#123;</div><div class="line">    Bundle bundle = (Bundle) state;</div><div class="line">    <span class="comment">// 取出父类的内容</span></div><div class="line">    Parcelable superData = bundle.getParcelable(KEY_SUPER_DATA);</div><div class="line">    <span class="comment">// 取出存储的矩形</span></div><div class="line">    mBoxen = (List&lt;Box&gt;) bundle.getSerializable(KEY_BOXEN);</div><div class="line">    <span class="keyword">super</span>.onRestoreInstanceState(superData);</div><div class="line">    invalidate();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="3-2-旋转矩形框"><a href="#3-2-旋转矩形框" class="headerlink" title="3.2 旋转矩形框"></a>3.2 旋转矩形框</h2><ol>
<li>在处理多点触控时我们需要用 <code>MotionEvent.getActionMasked()</code> 方法来获取事件 ID，<code>ACTION_POINTER_DOWN</code>指的是屏幕上已经有手指了（无论是几根，最大不超过【多点触控屏的极限 - 1】），另一根手指按下的情况。也就是说此时我们能知道两个手指按下了。</li>
<li><p>其次，图形的旋转一般是在绘制的时候旋转画布（canvas），需要的参数有旋转的角度（用度表示）以及旋转中心坐标，在这里我在 Box 类中加入了最开始的角度 <code>mOriginAngle</code>，已旋转后的角度 <code>mRotatedAngle</code> 两个成员变量，以及一个获取中心点坐标的方法。</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Box</span> </span>&#123;</div><div class="line">    	<span class="keyword">private</span> PointF mOrigin;</div><div class="line">    	<span class="keyword">private</span> PointF mCurrent;</div><div class="line">    	<span class="comment">// 此次按下时的角度</span></div><div class="line">    	<span class="keyword">private</span> <span class="keyword">float</span> mOriginAngle;</div><div class="line">    	<span class="keyword">private</span> <span class="keyword">float</span> mRotatedAngle; <span class="comment">// 已旋转的角度</span></div><div class="line"></div><div class="line">    	<span class="function"><span class="keyword">public</span> <span class="title">Box</span><span class="params">(PointF origin)</span> </span>&#123;</div><div class="line">        	mOrigin = origin;</div><div class="line">        	mCurrent = origin;</div><div class="line">        	mOriginAngle = <span class="number">0</span>;</div><div class="line">        	mRotatedAngle = <span class="number">0</span>;</div><div class="line">    	&#125;</div><div class="line">		<span class="comment">/** 省略 Getter 和 Setter **/</span></div><div class="line">	</div><div class="line">		<span class="comment">// 获取矩形的中心点</span></div><div class="line">    	<span class="function"><span class="keyword">public</span> PointF <span class="title">getCenter</span><span class="params">()</span> </span>&#123;</div><div class="line">        	<span class="keyword">return</span> <span class="keyword">new</span> PointF(</div><div class="line">                (mCurrent.x + mOrigin.x) / <span class="number">2</span>, </div><div class="line">                (mCurrent.y + mOrigin.y) / <span class="number">2</span>);</div><div class="line">    	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>对不同的触摸情况进行处理：</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">onTouchEvent</span><span class="params">(MotionEvent event)</span> </span>&#123;</div><div class="line">       PointF current = <span class="keyword">new</span> PointF(event.getX(), event.getY());</div><div class="line">       String action = <span class="string">""</span>;</div><div class="line"></div><div class="line">	<span class="comment">// 省略没有变化的部分</span></div><div class="line">       <span class="keyword">switch</span> (event.getActionMasked()) &#123;</div><div class="line">           <span class="keyword">case</span> MotionEvent.ACTION_POINTER_DOWN:</div><div class="line">               action = <span class="string">"POINTER_DOWN"</span>;</div><div class="line">               <span class="keyword">if</span> (event.getPointerCount() == <span class="number">2</span>) &#123;</div><div class="line">               <span class="comment">// 首先获取按下时的角度（有一个弧度转角度的过程）</span></div><div class="line">               <span class="comment">// 每次按下的时候将角度存入现在矩形的原始角度</span></div><div class="line">                   <span class="keyword">float</span> angle = (<span class="keyword">float</span>) (Math.atan((event.getY(<span class="number">1</span>) - event.getY(<span class="number">0</span>)) /</div><div class="line">                       (event.getX(<span class="number">1</span>) - event.getX(<span class="number">0</span>))) * <span class="number">180</span> / Math.PI);</div><div class="line">                   mCurrentBox.setOriginAngle(angle);</div><div class="line">               &#125;</div><div class="line">               <span class="keyword">break</span>;</div><div class="line"></div><div class="line">           <span class="keyword">case</span> MotionEvent.ACTION_MOVE:</div><div class="line">               action = <span class="string">"ACTION_MOVE"</span>;</div><div class="line">               <span class="keyword">if</span> (mCurrentBox != <span class="keyword">null</span>) &#123;</div><div class="line">               	<span class="comment">// 如果只有一只手指按下，而且还未曾旋转过的话，就进行大小的缩放</span></div><div class="line">                   <span class="keyword">if</span> (event.getPointerCount() == <span class="number">1</span> &amp;&amp; mCurrentBox.getRotatedAngle() == <span class="number">0</span>) &#123;</div><div class="line">                       mCurrentBox.setCurrent(current);</div><div class="line">                   &#125;</div><div class="line">                   <span class="comment">// 如果按下了两根手指</span></div><div class="line">                   <span class="keyword">if</span> (event.getPointerCount() == <span class="number">2</span>) &#123;</div><div class="line">                   	<span class="comment">// 获取角度</span></div><div class="line">                       <span class="keyword">float</span> angle = (<span class="keyword">float</span>) (Math.atan((event.getY(<span class="number">1</span>) - event.getY(<span class="number">0</span>)) /</div><div class="line">                               (event.getX(<span class="number">1</span>) - event.getX(<span class="number">0</span>))) * <span class="number">180</span> / Math.PI);</div><div class="line">                       Log.i(TAG, <span class="string">"onTouchEvent: angle:"</span> + (angle - mCurrentBox.getOriginAngle()));</div><div class="line">                       <span class="comment">// 已旋转的角度 = 之前旋转的角度 + 新旋转的角度</span></div><div class="line">                       <span class="comment">// 新旋转的角度 = 本次 move 到的角度 - 手指按下的角度</span></div><div class="line">                       mCurrentBox.setRotatedAngle(mCurrentBox.getRotatedAngle() + angle</div><div class="line">                               - mCurrentBox.getOriginAngle());</div><div class="line">                       <span class="comment">// 旋转角度变化后，初始角度也发生变化</span></div><div class="line">                       mCurrentBox.setOriginAngle(angle);</div><div class="line">                   &#125;</div><div class="line">                   invalidate();</div><div class="line">               &#125;</div><div class="line">               <span class="keyword">break</span>;</div><div class="line">       &#125;</div><div class="line"></div><div class="line">       <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">   &#125;</div></pre></td></tr></table></figure></li>
</ol>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017-03-02-cj0ag5y720022ifs68zlulcp4/" rel="next" title="Android编程权威指南（第二版）学习笔记（二十八）—— 第28章 网页浏览">
                <i class="fa fa-chevron-left"></i> Android编程权威指南（第二版）学习笔记（二十八）—— 第28章 网页浏览
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://kniost-comment-github.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
                                
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="kniost" />
          <p class="site-author-name" itemprop="name">kniost</p>
           
              <p class="site-description motion-element" itemprop="description">kniost 的成长与疑惑</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-自定义-View（定制视图）"><span class="nav-text">1. 自定义 View（定制视图）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-创建一个基本的自定义-View"><span class="nav-text">1.1 创建一个基本的自定义 View</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-处理触摸事件"><span class="nav-text">1.2 处理触摸事件</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-onDraw-方法内的图形绘制"><span class="nav-text">2. onDraw() 方法内的图形绘制</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-挑战练习"><span class="nav-text">3. 挑战练习</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-设备旋转问题"><span class="nav-text">3.1 设备旋转问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-旋转矩形框"><span class="nav-text">3.2 旋转矩形框</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">kniost</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'kniost-comment-github';
      var disqus_identifier = '2017-03-13-cj0ag5y78002bifs62vox4qyr/';

      var disqus_title = "Android编程权威指南（第二版）学习笔记（二十九）—— 第29章 定制视图与触摸事件";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
